<template>
	<div class="app-container">
		<!-- 顶部操作栏 -->
		<div class="page-header">
			<h2>报表模板配置</h2>
			<div class="operate-buttons">
				<el-button type="primary" icon="Plus" @click="handleAdd"
					>新增模板</el-button
				>
				<!-- <el-button
					type="warning"
					icon="Stop"
					@click="handleBatchDisable"
					:disabled="multiple"
					>批量停用</el-button
				> -->
				<el-button icon="Refresh" @click="handleRefresh">刷新列表</el-button>
			</div>
		</div>

		<!-- 搜索区域 -->
		<el-form
			:model="queryParams"
			ref="queryRef"
			:inline="true"
			label-width="100px"
		>
			<el-form-item label="模板名称" prop="templateName">
				<el-input
					v-model="queryParams.templateName"
					placeholder="请输入"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="模板编码" prop="templateCode">
				<el-input
					v-model="queryParams.templateCode"
					placeholder="请输入"
					clearable
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item
				label="所属业务模块"
				prop="businessModule"
				style="width: 200px"
			>
				<el-select
					v-model="queryParams.businessModule"
					placeholder="请选择"
					clearable
				>
					<el-option label="制水管理" value="water_production" />
					<el-option label="水质管理" value="quality" />
					<el-option label="设备管理" value="equipment" />
					<el-option label="能耗管理" value="energy" />
					<el-option label="安全生产" value="safety" />
				</el-select>
			</el-form-item>
			<el-form-item label="报表类型" prop="reportType" style="width: 200px">
				<el-select
					v-model="queryParams.reportType"
					placeholder="请选择"
					clearable
				>
					<el-option label="日报表" value="daily" />
					<el-option label="周报表" value="weekly" />
					<el-option label="月报表" value="monthly" />
					<el-option label="季度报表" value="quarterly" />
					<el-option label="自定义报表" value="custom" />
				</el-select>
			</el-form-item>
			<el-form-item label="状态" prop="templateStatus" style="width: 200px">
				<el-select
					v-model="queryParams.templateStatus"
					placeholder="请选择"
					clearable
				>
					<el-option label="草稿" value="draft" />
					<el-option label="已启用" value="enabled" />
					<el-option label="已停用" value="disabled" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery"
					>查询</el-button
				>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<!-- 模板列表 -->
		<el-table
			v-loading="loading"
			:data="templateList"
			@selection-change="handleSelectionChange"
		>
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="模板编码" align="center" prop="templateCode" />
			<el-table-column label="模板名称" align="center" prop="templateName" />
			<el-table-column
				label="所属业务模块"
				align="center"
				prop="businessModule"
			>
				<template #default="scope">{{
					formatBusinessModule(scope.row.businessModule)
				}}</template>
			</el-table-column>
			<el-table-column label="报表类型" align="center" prop="reportType">
				<template #default="scope">{{
					formatReportType(scope.row.reportType)
				}}</template>
			</el-table-column>
			<el-table-column label="状态" align="center" prop="templateStatus">
				<template #default="scope">
					<el-tag
						:type="
							scope.row.templateStatus === 'enabled'
								? 'success'
								: scope.row.templateStatus === 'disabled'
								? 'danger'
								: 'info'
						"
					>
						{{ formatStatus(scope.row.templateStatus) }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center">
				<template #default="scope">
					<el-button link type="primary" @click="handleView(scope.row)"
						>查看</el-button
					>
					<el-button link type="primary" @click="handleEdit(scope.row)"
						>编辑</el-button
					>
					<el-button
						link
						type="danger"
						@click="handleDisable(scope.row)"
						v-if="scope.row.templateStatus === 'enabled'"
					>
						停用
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页 -->
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 模板详情配置弹窗 -->
		<el-dialog
			:title="title"
			v-model="open"
			width="800px"
			append-to-body
			:close-on-click-modal="false"
		>
			<el-tabs v-model="activeTab" type="card">
				<!-- 基础信息配置 -->
				<el-tab-pane label="基础信息配置" name="baseInfo">
					<el-form
						ref="templateRef"
						:model="form"
						:rules="rules"
						label-width="120px"
					>
						<el-form-item label="模板名称" prop="templateName">
							<el-input
								v-model="form.templateName"
								placeholder="请输入"
								:disabled="viewOnly"
							/>
						</el-form-item>
						<el-form-item label="模板编码" prop="templateCode">
							<el-input v-model="form.templateCode" disabled />
						</el-form-item>
						<el-form-item label="所属业务模块" prop="businessModule">
							<el-select
								v-model="form.businessModule"
								placeholder="请选择"
								:disabled="viewOnly"
							>
								<el-option label="制水管理" value="water_production" />
								<el-option label="水质管理" value="quality" />
								<el-option label="设备管理" value="equipment" />
								<el-option label="能耗管理" value="energy" />
								<el-option label="安全生产" value="safety" />
							</el-select>
						</el-form-item>
						<el-form-item label="报表类型" prop="reportType">
							<el-select
								v-model="form.reportType"
								placeholder="请选择"
								:disabled="viewOnly"
							>
								<el-option label="日报表" value="daily" />
								<el-option label="周报表" value="weekly" />
								<el-option label="月报表" value="monthly" />
								<el-option label="季度报表" value="quarterly" />
								<el-option label="自定义报表" value="custom" />
							</el-select>
						</el-form-item>
						<el-form-item label="状态" prop="templateStatus">
							<el-select
								v-model="form.templateStatus"
								placeholder="请选择"
								:disabled="viewOnly"
							>
								<el-option label="草稿" value="draft" />
								<el-option label="已启用" value="enabled" />
								<el-option label="已停用" value="disabled" />
							</el-select>
						</el-form-item>
						<el-form-item label="模板描述" prop="templateDesc">
							<el-input
								v-model="form.templateDesc"
								type="textarea"
								rows="4"
								placeholder="请输入"
								:disabled="viewOnly"
							/>
						</el-form-item>
					</el-form>
				</el-tab-pane>

				<!-- 审核节点配置 -->
				<el-tab-pane label="审核节点配置" name="auditNodes">
					<div class="node-operate">
						<el-button
							type="primary"
							icon="Plus"
							@click="addAuditNode"
							:disabled="viewOnly"
						>
							新增审核节点
						</el-button>
					</div>
					<el-table :data="form.auditNodes" border style="margin-top: 10px">
						<el-table-column
							label="节点序号"
							align="center"
							prop="auditSort"
							width="80"
						/>
						<el-table-column label="节点名称" align="center" width="180">
							<template #default="scope">
								<el-input
									v-model="scope.row.nodeName"
									placeholder="请输入"
									:disabled="viewOnly"
								/>
							</template>
						</el-table-column>
						<el-table-column label="审核用户" align="center" width="180">
							<template #default="scope">
								<el-select
									v-model="scope.row.auditUserId"
									placeholder="请选择审核用户"
									:disabled="viewOnly"
								>
									<el-option
										v-for="user in auditUsers"
										:key="user.id"
										:label="user.name"
										:value="user.id"
									/>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="是否必填" align="center" width="120">
							<template #default="scope">
								<el-checkbox
									v-model="scope.row.isRequired"
									:true-label="1"
									:false-label="0"
									:disabled="viewOnly"
								/>
							</template>
						</el-table-column>
						<el-table-column
							label="操作"
							align="center"
							width="180"
							v-if="!viewOnly"
						>
							<template #default="scope">
								<el-button
									icon="Top"
									@click="moveNodeUp(scope.$index)"
									:disabled="scope.$index === 0"
								/>
								<el-button
									icon="Bottom"
									@click="moveNodeDown(scope.$index)"
									:disabled="scope.$index === form.auditNodes.length - 1"
								/>
								<el-button
									icon="Delete"
									type="danger"
									@click="deleteNode(scope.$index)"
								/>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancel">返回列表</el-button>
					<el-button type="primary" @click="submitForm" v-if="!viewOnly">
						保存
					</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 右侧审核用户面板 -->
		<!-- <div class="right-panel" v-if="activeTab === 'auditNodes' && open">
			<div class="panel-header">审核用户字典</div>
			<el-input
				v-model="userQuery"
				placeholder="搜索用户"
				clearable
				style="margin: 10px 0"
			/>
			<div class="role-list">
				<div
					class="role-item"
					v-for="user in filteredUsers"
					:key="user.id"
					:class="{
						active: form.auditNodes.some((n) => n.auditUserId === user.id),
					}"
					@click="selectUser(user)"
				>
					{{ user.name }}
				</div>
			</div>
		</div> -->
	</div>
</template>

<script setup name="ReportTemplate">
	import {
		ref,
		reactive,
		toRefs,
		getCurrentInstance,
		onMounted,
		computed,
	} from "vue";
	import {
		listTemplate,
		getTemplate,
		addTemplate,
		updateTemplate,
		disableTemplate,
		deleteTemplate,
		listAuditUsers,
	} from "@/api/prod_operate/sys_setting/table/reportTemplate";

	const { proxy } = getCurrentInstance();

	// 状态变量
	const loading = ref(true);
	const open = ref(false);
	const viewOnly = ref(false);
	const title = ref("");
	const activeTab = ref("baseInfo");
	const total = ref(0);
	const templateList = ref([]);
	const ids = ref([]);
	const single = ref(true);
	const multiple = ref(true);
	const auditUsers = ref([]); // 审核用户列表
	const userQuery = ref(""); // 用户搜索关键词

	// 数据模型
	const data = reactive({
		queryParams: {
			pageNum: 1,
			pageSize: 10,
			templateName: null,
			templateCode: null,
			businessModule: null,
			reportType: null,
			templateStatus: null,
		},
		form: {
			templateId: null,
			templateCode: null,
			templateName: null,
			businessModule: null,
			reportType: null,
			templateStatus: "draft",
			templateDesc: null,
			auditNodes: [],
		},
		rules: {
			templateName: [
				{ required: true, message: "请输入模板名称", trigger: "blur" },
			],
			businessModule: [
				{ required: true, message: "请选择所属业务模块", trigger: "change" },
			],
			reportType: [
				{ required: true, message: "请选择报表类型", trigger: "change" },
			],
			templateStatus: [
				{ required: true, message: "请选择模板状态", trigger: "change" },
			],
		},
	});

	const { queryParams, form, rules } = toRefs(data);

	// 页面初始化
	onMounted(() => {
		getList();
		getAuditUsers(); // 加载审核用户列表
	});

	// 获取模板列表
	function getList() {
		loading.value = true;
		listTemplate(queryParams.value)
			.then((response) => {
				templateList.value = response.rows;
				total.value = response.total;
				loading.value = false;
			})
			.catch((error) => {
				loading.value = false;
				proxy.$modal.msgError("加载失败：" + error.message);
			});
	}

	// 获取审核用户列表
	function getAuditUsers() {
		listAuditUsers()
			.then((response) => {
				auditUsers.value = response.data;
			})
			.catch((error) => {
				proxy.$modal.msgError("加载审核用户失败：" + error.message);
			});
	}

	// 格式化业务模块
	function formatBusinessModule(value) {
		const map = {
			water_production: "制水管理",
			quality: "水质管理",
			equipment: "设备管理",
			energy: "能耗管理",
			safety: "安全生产",
		};
		return map[value] || value;
	}

	// 格式化报表类型
	function formatReportType(value) {
		const map = {
			daily: "日报表",
			weekly: "周报表",
			monthly: "月报表",
			quarterly: "季度报表",
			custom: "自定义报表",
		};
		return map[value] || value;
	}

	// 格式化状态
	function formatStatus(value) {
		const map = {
			draft: "草稿",
			enabled: "已启用",
			disabled: "已停用",
		};
		return map[value] || value;
	}

	// 搜索
	function handleQuery() {
		queryParams.value.pageNum = 1;
		getList();
	}

	// 重置搜索
	function resetQuery() {
		proxy.resetForm("queryRef");
		handleQuery();
	}

	// 刷新列表
	function handleRefresh() {
		getList();
	}

	// 选择事件
	function handleSelectionChange(selection) {
		ids.value = selection.map((item) => item.templateId);
		single.value = selection.length !== 1;
		multiple.value = !selection.length;
	}

	// 新增模板
	function handleAdd() {
		resetForm();
		viewOnly.value = false;
		open.value = true;
		title.value = "新增报表模板";
		activeTab.value = "baseInfo";
	}

	// 查看模板
	function handleView(row) {
		viewOnly.value = true;
		open.value = true;
		title.value = "查看报表模板";
		getTemplate(row.templateId)
			.then((response) => {
				form.value = response.data;
			})
			.catch((error) => {
				proxy.$modal.msgError("加载详情失败：" + error.message);
			});
	}

	// 编辑模板
	function handleEdit(row) {
		viewOnly.value = false;
		open.value = true;
		title.value = "编辑报表模板";
		getTemplate(row.templateId)
			.then((response) => {
				form.value = response.data;
			})
			.catch((error) => {
				proxy.$modal.msgError("加载详情失败：" + error.message);
			});
	}

	// 停用模板
	function handleDisable(row) {
		proxy.$modal.confirm("是否停用该模板？停用后将无法生成报表").then(() => {
			disableTemplate(row.templateId)
				.then(() => {
					proxy.$modal.msgSuccess("停用成功");
					getList();
				})
				.catch((error) => {
					proxy.$modal.msgError("停用失败：" + error.message);
				});
		});
	}

	// 批量停用
	function handleBatchDisable() {
		proxy.$modal
			.confirm(`是否批量停用选中的${ids.value.length}个模板？`)
			.then(() => {
				Promise.all(ids.value.map((id) => disableTemplate(id)))
					.then(() => {
						proxy.$modal.msgSuccess("批量停用成功");
						getList();
					})
					.catch((error) => {
						proxy.$modal.msgError("批量停用失败：" + error.message);
					});
			});
	}

	// 新增审核节点
	function addAuditNode() {
		form.value.auditNodes.push({
			auditNodeId: null,
			nodeName: "",
			auditUserId: "",
			auditUserName: "",
			auditSort: form.value.auditNodes.length + 1,
			isRequired: 1,
		});
	}

	// 节点上移
	function moveNodeUp(index) {
		if (index > 0) {
			const temp = form.value.auditNodes[index];
			form.value.auditNodes[index] = form.value.auditNodes[index - 1];
			form.value.auditNodes[index - 1] = temp;
			updateNodeSort();
		}
	}

	// 节点下移
	function moveNodeDown(index) {
		if (index < form.value.auditNodes.length - 1) {
			const temp = form.value.auditNodes[index];
			form.value.auditNodes[index] = form.value.auditNodes[index + 1];
			form.value.auditNodes[index + 1] = temp;
			updateNodeSort();
		}
	}

	// 更新节点排序
	function updateNodeSort() {
		form.value.auditNodes.forEach((node, index) => {
			node.auditSort = index + 1;
		});
	}

	// 删除节点
	function deleteNode(index) {
		proxy.$modal.confirm("删除后不可恢复，是否确认？").then(() => {
			form.value.auditNodes.splice(index, 1);
			updateNodeSort();
			if (form.value.auditNodes.length === 0) {
				proxy.$modal.msgWarning("请至少配置1个审核节点");
			}
		});
	}

	// 筛选用户
	const filteredUsers = computed(() => {
		if (!userQuery.value) return auditUsers.value;
		return auditUsers.value.filter((user) =>
			user.name.includes(userQuery.value)
		);
	});

	// 选择用户
	function selectUser(user) {
		if (form.value.auditNodes.length > 0) {
			form.value.auditNodes[form.value.auditNodes.length - 1].auditUserId =
				user.id;
			form.value.auditNodes[form.value.auditNodes.length - 1].auditUserName =
				user.name;
		} else {
			addAuditNode();
			form.value.auditNodes[0].auditUserId = user.id;
			form.value.auditNodes[0].auditUserName = user.name;
		}
	}

	// 表单重置
	function resetForm() {
		form.value = {
			templateId: null,
			templateCode: null,
			templateName: null,
			businessModule: null,
			reportType: null,
			templateStatus: "draft",
			templateDesc: null,
			auditNodes: [],
		};
		proxy.resetForm("templateRef");
	}

	// 取消
	function cancel() {
		open.value = false;
		resetForm();
	}

	// 提交表单
	function submitForm() {
		proxy.$refs["templateRef"].validate((valid) => {
			if (valid) {
				// 校验审核节点
				if (
					form.value.templateStatus === "enabled" &&
					form.value.auditNodes.length === 0
				) {
					return proxy.$modal.msgWarning("请配置至少1个审核节点");
				}

				// 提交数据
				if (form.value.templateId) {
					updateTemplate(form.value)
						.then(() => {
							proxy.$modal.msgSuccess("更新成功");
							open.value = false;
							getList();
						})
						.catch((error) => {
							proxy.$modal.msgError("更新失败：" + error.message);
						});
				} else {
					addTemplate(form.value)
						.then(() => {
							proxy.$modal.msgSuccess("新增成功");
							open.value = false;
							getList();
						})
						.catch((error) => {
							proxy.$modal.msgError("新增失败：" + error.message);
						});
				}
			}
		});
	}
</script>

<style scoped>
	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
		padding-bottom: 8px;
		border-bottom: 1px solid #eee;
	}

	.operate-buttons {
		display: flex;
		gap: 8px;
	}

	.node-operate {
		margin-bottom: 10px;
		text-align: right;
	}

	.right-panel {
		position: fixed;
		top: 0;
		right: 0;
		width: 300px;
		height: 100%;
		background: #fff;
		border-left: 1px solid #eee;
		padding: 16px;
		box-shadow: -2px 0 10px rgba(0, 0, 0, 0.05);
		z-index: 1000;
	}

	.panel-header {
		font-weight: bold;
		margin-bottom: 10px;
		padding-bottom: 8px;
		border-bottom: 1px solid #eee;
	}

	.role-list {
		max-height: calc(100vh - 120px);
		overflow-y: auto;
	}

	.role-item {
		padding: 8px 12px;
		margin-bottom: 8px;
		border-radius: 4px;
		cursor: pointer;
		transition: all 0.2s;
	}

	.role-item:hover {
		background-color: #f5f7fa;
	}

	.role-item.active {
		background-color: #e6f7ff;
		border-left: 3px solid #1890ff;
	}
</style>
